package net.xinqushi.socket.nio;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @author xjie 2019/7/17 14:07
 * @description  a blocked channelClient , 阻塞式的channel与Socket 阻塞特性一致
 */
public class BlockClient {
    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("localhost", 6666));
        ByteBuffer buf = ByteBuffer.allocate(48);
        String newData = "New String to write to file..." + System.currentTimeMillis();
        buf.put(newData.getBytes());
        buf.flip();//ready for read
        while(buf.hasRemaining()) {
            socketChannel.write(buf);
        }
        //read from server
/*        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int readBytes = 0;
        while ( -1 != ( readBytes = socketChannel.read(buf)) ){
            bos.write(buf.array() , 0 , readBytes);
        }
        System.out.println(new String(bos.toByteArray()));*/
        socketChannel.close();//标识end ,server read -1 , 否则BlockServer 读取到末尾会阻塞，无法判断client是否写入结束
    }
}
